package no.ntnu.fp.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPListener implements Runnable {
	
	private Server server;
	private ServerSocket socket;
	
	public TCPListener(Server server) {
		this.server = server;
		
		try {
			socket = new ServerSocket(1502);
		} catch (IOException e) {
			System.err.println("ServerSocket not created");
		}
	}
	
	@Override
	public void run() {
		listen();
	}
	
	private void listen() {
		System.out.println("Listening to incoming connections");
		while (true) {
			
			try {
				Socket client = socket.accept();
				
				if (client != null) {
					server.addClient(client);
				}
			} catch (IOException e) {
				System.err.println("IOException on accept");
			} catch (NullPointerException e) {}

			try {
				Thread.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	
		}
	}
}
